package com.woniu.controller;

import com.woniu.util.MinIOUtils;
import com.woniu.util.ResponseData;
import io.minio.ObjectWriteResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private MinIOUtils minioUtils;


    /*
    上传文件类型，只能用post
    multipartFile用于接收文件
     */
    @PostMapping("/img")
    public ResponseData<?> uploadImg(MultipartFile file, HttpServletRequest request) {
        String path="";
        try {
            String bucketName="chargex";
            String originalFilename = file.getOriginalFilename();
            String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
            //1:session获取用户id
            //2：修改数据库中文件地址
            ObjectWriteResponse response = minioUtils.uploadFile(bucketName,file,fileName,"image/png");
            System.out.println(response.etag());
            System.out.println(minioUtils.getBasisUrl()+fileName);
            path=minioUtils.getBasisUrl()+fileName;
            HttpSession session = request.getSession();
//            User user = (User) session.getAttribute("user");
//            user.setImgSrc(String.valueOf(responseData.getData()));
//            userService.updateUserImgSrc(user);
//            return responseData;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return new ResponseData<>().ok(path);
    }
}
